//
//  Transcript.swift
//  hello
//
//  Created by 赵康 on 2024/11/11.
//

import Fluent
import Vapor

final class Transcript: Model, Content, @unchecked Sendable {
	static var schema: String { SchemaEnum.transcripts.rawValue }
	
	@ID(key: .id)
	var id: UUID?
	
	@Field(key: FieldKeys.sentence)
	var sentence: String
	
	@Field(key: FieldKeys.translation)
	var translation: String
	
	@Field(key: FieldKeys.startTime)
	var startTime: TimeInterval
	
	@Field(key: FieldKeys.endTime)
	var endTime: TimeInterval
	
	@Field(key: FieldKeys.wordCount)
	var wordCount: Int
	
	@Parent(key: FieldKeys.audio)
	var audio: Audio
	
	@OptionalField(key: FieldKeys.isDeleted)
	var isDeleted: Bool?
	
	@Timestamp(key: FieldKeys.createdAt, on: .create)
	var createdAt: Date?
	
	@Timestamp(key: FieldKeys.updatedAt, on: .update)
	var updatedAt: Date?
	
	init() { }
	
	init(
		id: UUID? = nil,
		sentence: String,
		translation: String,
		startTime: TimeInterval,
		endTime: TimeInterval,
		wordCount: Int,
		isDeleted: Bool?,
		createdAt: Date?,
		updatedAt: Date?,
		audioID: Audio.IDValue
	) {
		self.id = id
		self.sentence = sentence
		self.translation = translation
		self.startTime = startTime
		self.endTime = endTime
		self.$audio.id = audioID
		self.wordCount = wordCount
		self.isDeleted = isDeleted
		self.createdAt = createdAt
		self.updatedAt = updatedAt
	}
}

extension Transcript {
	func updateWordCount(on db: Database) async throws {
		let newWordCount = ArabicWordCounter.countWords(self.sentence)
		let oldWordCount = self.wordCount
		
		if newWordCount != oldWordCount {
			self.wordCount = newWordCount
			try await self.save(on: db)
			
			// 更新专辑的总词数
			try await self.$audio.load(on: db)
			try await self.audio.$album.load(on: db)
			
			let difference = newWordCount - oldWordCount
			self.audio.album.wordCount += difference
			try await self.audio.album.save(on: db)
		}
	}
}

// 在 Transcript.swift 中添加
extension Transcript {
	// 处理句子中的标点符号
	func processPunctuation() {
		self.sentence = PunctuationConverter.convertChineseToArabicPunctuation(self.sentence)
	}
}
